/**
 * @file ajax
 * @date 20180703
 * @author wangwenfa
 */
import Vue from 'vue';
import router from './../router';
import axios from 'axios';
import store from '../store';
// import qs from 'qs';
import cookie from '../utils/cookie.js';
import { Encrypt, Decrypt } from '../plugins/aes.js';
import noEncrypt from '../api/noEncryptApi.js';
import { isJsonString } from '../commons/function.js'
const defaultHeaders = {
	Accept: 'application/json, text/plain, */*; charset=utf-8',
	'Content-Type': 'application/json; charset=utf-8',
	Pragma: 'no-cache',
	'Cache-Control': 'no-cache'
};

// 设置默认头
Object.assign(axios.defaults.headers.common, defaultHeaders);
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
axios.defaults.withCredentials = false;
axios.defaults.baseURL = store.state.prefix
// http request 拦截器
axios.interceptors.request.use(
	config => {
		let condata = false
		if (config.method == 'post') {
			if (config.data.logcaldata) {
				let condatatwo = config.data.logcaldata;
				if (condatatwo != null && condatatwo != undefined && condatatwo == true) {
					condata = true
				}
			}
		}
		//处理登录加密
		if (condata == true) {
			config.headers["FORM-ENCODE"] = ((config.method === 'get' && !config.data) || (store.state.env == "test")) ? 2 : 2;
		} else {
				let RegObj = new RegExp('(operate/login)|(filemd5)', 'ig');
				Vue.prototype.fromData = {
					'ContentType': 'multipart/form-data',
					'Authorization': "Bearer " + window.localStorage.getItem('access_token')
				}
				// let fileObj = new RegExp("hospital/uploadOperateFiles", 'ig')
				// let excelObj = new RegExp("xk/purchase/exportDhtboPurchase", 'ig')
				// let jiayiReportExport = new RegExp("fds/reports/recordReportExport", 'ig')
				// let contractReportExport = new RegExp("fds/reports/contractReportExport", 'ig')
				// let tubesListExport = new RegExp("collectTubes/tubesListExport", 'ig')
				// let nullifyAppointmentListExport = new RegExp("collectTubes/nullifyAppointmentListExport", 'ig')
				// let positiveAppointmentListExport = new RegExp("/collectTubes/positiveAppointmentListExport", 'ig')
				// let taskLocationInfoExport = new RegExp("/collect/taskInfo/taskLocationInfoExport", 'ig')
				// let writeExcel = new RegExp("/appointment/record/writeExcel", 'ig')
				// if (!RegObj.test(config.url)) {
				// 	if (!fileObj.test(config.url)) {
				// 		if (!excelObj.test(config.url)) {
				// 			if (!jiayiReportExport.test(config.url)) {
				// 				if (!contractReportExport.test(config.url)) {
				// 					if (!tubesListExport.test(config.url)) {
				// 						if (!nullifyAppointmentListExport.test(config.url)) {
				// 							if (!positiveAppointmentListExport.test(config.url)) {
				// 								if (!taskLocationInfoExport.test(config.url)) {
				// 									if (!writeExcel.test(config.url)) {
				// 										let iv = store.state.iv;
				// 										let salt = store.state.salt;
				// 										let key = cookie.getCookie("randmId");
				// 										if (!cookie.getCookie("access_user")) {
				// 											router.push("/login")
				// 											return false;
				// 										}
				// 										let data
				// 										if (config.data != null && config.data.method == 'GET') {
				// 											data = { version: store.state.version, uri: config.data.uri, method: 'GET' }
				// 										} else {
				// 											data = { version: store.state.version, uri: config.url, method: config.method.toUpperCase(), 'body': config.data }
				// 										}
				// 										config.url = '/api';
				// 										let access_user = Decrypt(key, iv, cookie.getCookie("access_user"));
				// 										console.log(key+ " -- "+ iv + " -- "+cookie.getCookie("access_user"))
				// 										console.log(access_user);

				// 										config.headers["OPERATE-USER"] = access_user;
				// 										config.headers["FORM-ENCODE"] = ((config.method === 'get' && !config.data) || (store.state.env == "test")) ? 1 : 1;
				// 										let tdata = JSON.stringify(data);
				// 										tdata = Encrypt(key, iv, tdata);
				// 										config.headers["FORM-ENCODE"] === 1 && (config.data = { data: tdata });
				// 									}
				// 								}
				// 							}
				// 						}
				// 					}
				// 				}
				// 			}
				// 		}
				// 	}
				// }
				let access_token = window.localStorage.getItem('access_token');
				if (access_token != undefined)
					config.headers.Authorization = "Bearer " + access_token;

		}
		return config;
	},
	err => {
		return Promise.reject(err);
	}
);
// http response 拦截器
axios.interceptors.response.use(
	response => {
		if (response.data.code === 401) {
			alert("Token已失效,请重新登录重试!")
			router.push("/login")
			return Promise.reject(response);
		}
		let iv = store.state.iv;
		let loginkeytemp = store.state.loginkeytemp;
		let key = cookie.getCookie("randmId");
		let form = response.config.headers["FORM-ENCODE"]
		let condata = false
		let condatatwo = false
		let status = isJsonString(response.config.data)
		console.log(status)
		if (status) {
			condatatwo = JSON.parse(response.config.data).logcaldata;
		}
		if (condatatwo != null && condatatwo != undefined && condatatwo == true) {
			condata = true
		}
		if (condata == true) {
			let tmpData = response.data.object;
			if (tmpData != null) {
				response.data.object = JSON.parse(Decrypt(loginkeytemp, iv, tmpData));
			}
		} else {
			let tmpData = response.data.object;
			let fileObj = new RegExp("hospital/uploadOperateFiles", 'ig')
			if (!fileObj.test(response.config.url)) {
				if (tmpData && form != 0 && response.data.encryption) {
					response.data.object = JSON.parse(Decrypt(key, iv, tmpData));
				}
			}
		}
		console.log("回参", response);
		return response;
	},
	error => {
		Vue.prototype.$Message.error('接口异常请联系管理员')
		return Promise.reject(error);
	}
)
export default axios;
